<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
    <el-form-item label="模型标识" prop="identifier">
      <el-input v-model="formData.identifier"></el-input>
    </el-form-item>
    <el-form-item label="模型名称" prop="name">
      <el-input v-model="formData.name"></el-input>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="formData.remark"></el-input>
    </el-form-item>
    <el-form-item label="字段" prop="fieldList">
      <VueDraggable class="w-100%" v-model="formData.fieldList" handle=".handle" target="tbody" :animation="150">
        <el-table border :data="formData.fieldList" style="width: 100%">
          <el-table-column label="" width="60" prop="" align="center">
            <template #header>
              <div class="flex items-center justify-center">
                <el-icon size="20" title="添加字段" @click="openSelectField" class="cursor-pointer">
                  <CirclePlus />
                </el-icon>
              </div>
            </template>
            <template #default>
              <el-icon class="handle cursor-pointer">
                <Rank />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="字段标识" width="180" prop="title">
            <template #default="{ row }">
              <div>{{ row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="字段名称" width="180" prop="title">
            <template #default="{ row }">
              <div>{{ row.title }}<span v-if="row.required" class="color-red">*</span></div>
            </template>
          </el-table-column>
          <el-table-column label="字段类型" width="180" prop="type" align="center"> </el-table-column>
          <el-table-column label="是否必填" width="180" prop="required" align="center">
            <template #default="{ row }">
              <div>{{ row.required ? '是' : '否' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="默认值" width="180" prop="defaultValue" align="center">
            <template #default="{ row }">
              <div>{{ row.defaultValue || '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="字段描述" prop="remark">
            <template #default="{ row }">
              <div>{{ row.remark || '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="{ $index, row }">
              <el-button icon="Edit" @click="handleEdit($index, row)"></el-button>
              <el-button type="danger" icon="Delete" @click="handleDelete($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </VueDraggable>
    </el-form-item>
    <el-form-item>
      <el-button @click="handleSubmitAddModel" type="primary">提交</el-button>
      <el-button @click="$router.back()">取消</el-button>
    </el-form-item>
  </el-form>
  <add-field ref="addFieldFormRef" @submit-field="submitField"></add-field>
</template>
<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import { createModel, createView } from '@/api/model'
import addField from './add-field.vue'
import { ElMessage, type ElForm } from 'element-plus'
import { useRouter } from 'vue-router'

const addFieldRef = useTemplateRef<typeof addField>('addFieldFormRef')
const formData = ref<{ name: string; remark: string; identifier: string; fieldList: any[] }>({
  name: '',
  remark: '',
  identifier: '',
  fieldList: [],
})
const addModelRef = useTemplateRef<InstanceType<typeof ElForm>>('formRef')
const editIndex = ref<number>(0)

const router = useRouter()
const rules = ref({
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
  ],
  identifier: [
    { required: true, message: '请输入模型标识符', trigger: 'blur' },
  ],
})


const submitField = (data: any, type: string) => {
  if (type === 'create') {
    formData.value.fieldList.push(data)
  } else {
    formData.value.fieldList.splice(editIndex.value, 1, data)
  }
}

const handleDelete = (index: number) => {
  formData.value.fieldList.splice(index, 1)
}

const openSelectField = () => {
  addFieldRef.value?.openAddFieldDialog('create')
}

const handleEdit = (index: number, row: any) => {
  editIndex.value = index
  addFieldRef.value?.openAddFieldDialog('edit', JSON.parse(JSON.stringify(row)))
}

const handleSubmitAddModel = () => {
  addModelRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    const obj = formData.value
    const res: any = await createModel(obj)
    const viewInfo: any = {
      modelIdentifier: obj.identifier,
      identifier: "list",
      name: "列表",
      columns: []
    }
    obj.fieldList.map(v => {
      viewInfo.columns.push({
        name: v.name,
        type: v.type,
        title: v.title,
        width: 100,
        display: true
      })
    })
    const viewRes: any = await createView(viewInfo)
    if (res.code === 0 && viewRes.code === 0) {
      ElMessage.success('创建成功')
      router.back()
    }
  })
}

</script>
<style scoped></style>
